<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Chargecode;
use app\admin\model\Notice;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopfav;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptuan;
use app\admin\model\Shopwifi;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Userweixin;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Shop extends Api
{
    protected $noNeedLogin = ['chargeNotify','getVideo','sxfCallback','shopList','getChargeInfo','roomInfo','getNotice','roomTime','getRoomList','getRoomListV2','getRoomListV3','getRoomListV4','getDetail','getListV2','getMallShopList','getQpRoomList'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function _initialize()
    {
        parent::_initialize();

    }

    public function getVideo()
    {

        $id  = $this->request->param('id');
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$id)->find();
        $this->success('',$shop['video']);
    }

    public function shopList()
    {

        $keyword = $this->request->param('keyword');
        $orgId = $this->request->param('orgId');
        $where = array();
        $where['org_id'] = $orgId;
        if ($keyword != '') {
            $where['name'] = array('like', "'%" . $keyword . "%'");
        }
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->where($where)->select();
        $this->success('', $list);
    }

    public function shopList2()
    {

        $keyword = $this->request->param('keyword');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');

        if(!$lat){
            $lat =28.2068360;
            $lng =112.8823270;
        }

        $orgId = $this->request->param('orgId');

        $where = "";
        if ($keyword != '') {
            $where ="where name like '%".$keyword."%'";
        }

        $sql = "select * from(
SELECT id,name,address,logo,lng,lat,is_join_balance,org_id,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop  $where )  as tmp_table_name
order by distance";

        //error_log("==sql==".$sql);
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->query($sql);
        $this->success('', $list);
    }


    public function shopList3()
    {

        $keyword = $this->request->param('keyword');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');

        if(!$lat){
            $lat =28.2068360;
            $lng =112.8823270;
        }

        $orgId = $this->request->param('orgId');

        $where = "";
        if ($keyword != '') {
            $where ="where name like '%".$keyword."%'";
        }
        if($where != ""){
            $where .= " and qun_url != ''";
        }else{
            $where = " where qun_url != ''";

        }

        $sql = "select * from(
SELECT id,name,address,logo,lng,lat,is_join_balance,qun_url,org_id,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop  $where )  as tmp_table_name
order by distance";

       // error_log("==sql==".$sql);
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->query($sql);
        foreach ($list as $key=>$val){
            $list[$key]['qun_url'] = cdnurl($val['qun_url'],true);
        }
        $this->success('', $list);
    }

    /**
     * 获取店铺充值套餐和用户店铺与额
     */
    public function getChargeInfo()
    {

        $user = $this->auth->getUser();
        $shop_id = $this->request->param('shop_id');

        $shopChargeConfigModel = new Shopchargeconfig();
        $chargeList = $shopChargeConfigModel->where('shop_id', $shop_id)->order('amount', 'asc')->select();

        $ret = array();
        $userBalanceModel = new Userbalance();
        $totalAmount = $userBalanceModel->balance($shop_id,$user['id']);


        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);

        $ret['balance'] = formatMoney($totalAmount+$allBalance);
        $ret['chargeList'] = $chargeList;
        $ret['shopBalance'] = formatMoney($totalAmount);//店铺余额
        $ret['allBalance'] = $allBalance;//平台余额

        $this->success('', $ret);

    }


    public function doCharge()
    {

        $user = $this->auth->getUser();
        $charge_id = $this->request->param('charge_id');
        $orgId = $this->request->param('orgId');
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$charge['shop_id'])->find();
        if($orgId == ''){
            $orgId = $shop['org_id'];
        }
        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];
        $dbCharge['org_id'] = $orgId;


        $dbCharge['pay_rate'] =formatMoney($shop['pay_rate']* $dbCharge['amount']/100);
        $dbCharge['rate'] =formatMoney($shop['ratio']* $dbCharge['amount']/100);



        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

//            $params = [
//                'out_trade_no' => $order_no,//你的订单号
//                'total_fee' => $charge['amount'] * 100,//单位元
//                'body' => $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'],
//                'openid' => $wx['openid'],
//
//            ];
//
//            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/chargeNotify";
//            $config = Service::getConfig("wechat");
//            $config['notify_url'] = $url;
//            $pay = Pay::wechat($config);
//            $result = $pay->miniapp($params);

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/sxfCallback";


            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();

            $shopMnoModel =new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
            $mno = $org['mno'];
            if($shopMno){
                if($shopMno['ratio'] == 100){
                    //走挂靠
                    $mno = $shopMno['mno'];
                }else{
                    //走分账
                    $fusruleId = array();
                    $fusruleId['mno'] = $shopMno['mno'];

                    $realPay = formatMoney( $charge['amount']-  $charge['amount']*0.006);
                    $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);

                    $fs = array();
                    $fs[] = $fusruleId;
                    $req['fusruleId'] = $fs;
                }
            }
            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();
            $req['mno'] = $mno;//纷享未来药房
            $req['ordNo'] = $order_no;
            $req['amt'] =   $charge['amount'];

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";

            $req['subAppid'] = "wx4abd56997bacbaee";
            $req['userId'] = $wx['openid'];
            $body =  $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = "店铺会员充值";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            error_log("===req===".json_encode($req));


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }




        } else {
            $this->error("充值失败，请联系客服");
        }


    }


    public function doChargeFz()
    {

        $user = $this->auth->getUser();
        $charge_id = $this->request->param('charge_id');
        $orgId = $this->request->param('orgId');
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$charge['shop_id'])->find();
        if($orgId == ""){
            $orgId = $shop['org_id'];
        }
        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];
        $dbCharge['org_id'] = $orgId;


        $dbCharge['pay_rate'] =formatMoney($shop['pay_rate']* $dbCharge['amount']/100);
        $dbCharge['rate'] =formatMoney($shop['ratio']* $dbCharge['amount']/100);



        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

//            $params = [
//                'out_trade_no' => $order_no,//你的订单号
//                'total_fee' => $charge['amount'] * 100,//单位元
//                'body' => $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'],
//                'openid' => $wx['openid'],
//
//            ];
//
//            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/chargeNotify";
//            $config = Service::getConfig("wechat");
//            $config['notify_url'] = $url;
//            $pay = Pay::wechat($config);
//            $result = $pay->miniapp($params);

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/sxfCallback";




            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();


            error_log($shop['id']."==org==".json_encode($org));
            $shopMnoModel =new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
            $mno = $org['mno'];
            if($shopMno){
                if($shopMno['ratio'] == 100){
                    //走挂靠
                    $mno = $shopMno['mno'];
                }else{
                    //走分账
                    $pay_price =$charge['amount'];
                    $listMnos = $shopMnoModel->where('shop_id',$shop['id'])->select();
                    $fs = array();
                    $realPay = formatMoney($pay_price- $pay_price*0.006);
                    foreach ($listMnos as $key=>$val){
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $val['mno'];
                        $fusruleId['allotValue'] = formatMoney($val['ratio']*$realPay/100);
                        $fs[] = $fusruleId;
                    }
                    $req['fusruleId'] = $fs;
                }
            }



            $req['mno'] = $mno;
            $req['ordNo'] = $order_no;
            $req['amt'] =   $charge['amount'];

            error_log("===req==".json_encode($req));

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];
            $body =  $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = $body;
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;




            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);

            error_log("====res===".json_encode($res));
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }




        } else {
            $this->error("充值失败，请联系客服");
        }


    }


    public function doChargeFzMore()
    {

        $user = $this->auth->getUser();
        $charge_id = $this->request->param('charge_id');
        $orgId = $this->request->param('orgId');
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$charge['shop_id'])->find();
        if($orgId == ""){
            $orgId = $shop['org_id'];
        }
        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];
        $dbCharge['org_id'] = $orgId;


        $dbCharge['pay_rate'] =formatMoney($shop['pay_rate']* $dbCharge['amount']/100);
        $dbCharge['rate'] =formatMoney($shop['ratio']* $dbCharge['amount']/100);



        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

//            $params = [
//                'out_trade_no' => $order_no,//你的订单号
//                'total_fee' => $charge['amount'] * 100,//单位元
//                'body' => $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'],
//                'openid' => $wx['openid'],
//
//            ];
//
//            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/chargeNotify";
//            $config = Service::getConfig("wechat");
//            $config['notify_url'] = $url;
//            $pay = Pay::wechat($config);
//            $result = $pay->miniapp($params);

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/sxfCallback";




            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();


            error_log($shop['id']."==org==".json_encode($org));
            $shopMnoModel =new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
            $mno = $org['mno'];
            if($shopMno){
                if($shopMno['ratio'] == 100){
                    //走挂靠
                    $mno = $shopMno['mno'];
                }else{
                    //走分账
                    $pay_price =$charge['amount'];

                    $listMnos = $shopMnoModel->where('shop_id',$shop['id'])->select();
                    $fs = array();
                    $realPay = formatMoney($pay_price- $pay_price*0.006);
                    foreach ($listMnos as $key=>$val){
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $val['mno'];
                        $fusruleId['allotValue'] = formatMoney($val['ratio']*$realPay/100);
                        $fs[] = $fusruleId;

                    }

                    $req['fusruleId'] = $fs;
                }
            }



            $req['mno'] = $mno;
            $req['ordNo'] = $order_no;
            $req['amt'] =   $charge['amount'];

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];
            $body =  $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = $body;
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }




        } else {
            $this->error("充值失败，请联系客服");
        }


    }

    public function sxfCallback(){

        $param = file_get_contents("php://input");
        error_log("===order===callback=====" . json_encode($param));

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $shopChargeModel = new Shopcharge();
            $order = $shopChargeModel->where('order_no', $out_trade_no)->find();
            $shopChargeModel->where('id',$order['id'])->update(['status'=>'payed']);
            $userBalanceModel = new Userbalance();
            $shopchargeconfigModel = new Shopchargeconfig();
            $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
            $balance = $userBalanceModel->where('b_type','charge')->where('order_id',$order['id'])->find();
            if(!$balance){
                $userBalanceModel->insert(['user_id'=>$order['user_id'],'type'=>'in','amount'=>$charge['get_amount'],'create_time'=>time(),
                    'shop_id'=>$charge['shop_id'],'order_id'=>$order['id'],"mark"=>"用户充".$charge['amount']."得".$charge['get_amount']]);

                $shopModel = new \app\admin\model\Shop();
                $shop = $shopModel->where('id',$charge['shop_id'])->find();


                /**
                 * 商家分润
                 */


                $pay_price = $order['amount'];
                $pay_rate = formatMoney( $pay_price*0.006);
                $shopProfit = $pay_price-formatMoney($shop['ratio']*$pay_price/100)-$pay_rate;
                $shopOrderProfitModel  = new Shoporderprofit();
                $shopOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$charge['shop_id'],'type'=>'charge',
                    'user_id'=>$shop['user_id'],'create_time'=>time(),'amount'=>$shopProfit]);


                /**
                 * 代理商分润
                 */
                if($shop['agent_ratio'] > 0){

                    $userOrderProfitModel = new Userorderprofit();
                    $agentFee = $shop['agent_ratio']*$order['amount']/100;
                    if($agentFee > 0){
                        $userOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$charge['shop_id'],'type'=>'charge',
                            'user_id'=>$shop['agent_id'],'create_time'=>time(),'amount'=>formatMoney($agentFee)]);
                    }


                }
            }

        }
    }

    public function chargeNotify()
    {

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {

            $shopChargeModel = new Shopcharge();
            $order = $shopChargeModel->where('order_no', $out_trade_no)->find();
            $shopChargeModel->where('id',$order['id'])->update(['status'=>'payed']);
            $userBalanceModel = new Userbalance();
            $shopchargeconfigModel = new Shopchargeconfig();
            $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
            $userBalanceModel->insert(['user_id'=>$order['user_id'],'type'=>'in','amount'=>$charge['get_amount'],'create_time'=>time(),
                'shop_id'=>$charge['shop_id'],'order_id'=>$order['id'],"mark"=>"用户充".$charge['amount']."得".$charge['get_amount']]);

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id',$charge['shop_id'])->find();


            /**
             * 商家分润
             */
            $shopOrderProfitModel  = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$charge['shop_id'],'type'=>'charge',
                'user_id'=>$shop['user_id'],'create_time'=>time(),'amount'=>formatMoney(($order['amount']-$order['rate']-$order['pay_rate']))]);


            /**
             * 代理商分润
             */
            if($shop['agent_ratio'] > 0){

                $userOrderProfitModel = new Userorderprofit();
                $agentFee = $shop['agent_ratio']*$order['amount']/100;
                if($agentFee > 0){
                    $userOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$charge['shop_id'],'type'=>'charge',
                        'user_id'=>$shop['agent_id'],'create_time'=>time(),'amount'=>formatMoney($agentFee)]);
                }


            }

        }
        return $pay->success();

    }

    public function getDetail(){

        $id = $this->request->param('id');
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$id)->find();
        $shop['logo'] = cdnurl($shop['logo'],true);

        if($shop['video'] != ""){
            $shop['video']  = cdnurl($shop['video'],true);
        }
        $cover = array();
        if($shop['cover'] != ""){
            $covers = explode(",",$shop['cover']);

            foreach ($covers as $key=>$val){
                $cover[] = cdnurl($val,true);
            }
        }else{
            $cover[] = 'https://resouce.51fxyf.com/default_room_bg.jpg';

        }
        $tag = array();
        if($shop['tag'] != ""){
            $tag = explode(",",$shop['tag']);
        }
        if($shop['wx_code'] != ""){
            $shop['wx_code'] = cdnurl($shop['wx_code'],true);
        }

        $shop['cover']= $cover;
        $shop['tag']= $tag;

        $shopFavModel = new Shopfav();

        $isFav = -1;
        $fav = $shopFavModel->where('shop_id',$shop['id'])->find();
        if($fav){
            $isFav = 1;
        }
        $shop['isFav'] = $isFav;

        $shopTuanModel = new Shoptuan();
        $tuanList = $shopTuanModel->where('shop_id',$shop['id'])->where('status',1)->select();
        $shop['tuanList'] = $tuanList;
        $shop['status_txt'] =  $shopModel->getStatus($shop['status']);
        $this->success('',$shop);

    }

    public function getRoomList(){

        $shop_id = $this->request->param('shop_id');
        $spec = $this->request->param('spec');
        $shopRoomModel = new Shoproom();

        if($spec == '') $spec =-1;
        //根据包厢状态排序，自动将空闲包厢置顶
        if($spec == -1){
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->order(['status'=>'asc','weigh'=>'desc'])->select();
        }else{
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('spec',$spec)->order(['status'=>'asc','weigh'=>'desc'])->select();

        }

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $isClean = $shop['is_clean_book'];
        $shopBookTime = new Shoproombook();
        $roomCleanModel = new Roomclean();

        $cleanList = $roomCleanModel->where('shop_id',$shop_id)->where('start_time',"<",time())->where('end_time',">",time())->where('status','in',['undo','doing'])->select();

        foreach ($list as $key=>$val){


            $setList = $val['set'];

            $setArrayList = array();
            if(count($setList) > 3){
                foreach ($setList as $k=>$v){
                    if($k <2){
                        $setArrayList[] = $v;
                    }
                }
                error_log("====setList count2=====".count($setArrayList));
                $list[$key]['set2'] = $setArrayList;
            }else{
                $list[$key]['set2'] = $setList;

            }

            $list[$key]['logo'] = cdnurl($val['logo'],true);

            $covers = explode(",",$val['cover']);
            $cover = array();
            foreach ($covers as $k=>$v){
                if($v != ""){
                    $cover[] =   cdnurl($v,true);
                }
            }
            $list[$key]['cover'] = $cover;
            $tag = explode(",",$val['tag']);
            $tags = array();
            foreach ($tag as $k=>$v){
                if($v != ""){
                    if($k <7){
                        $tags[] = $v;
                    }
                }
            }
            $list[$key]['tag'] = $tags;
            $time = getHourSlot();
            $list[$key]['useEndTime'] = -1;

            $endTime = "";
            $bookList = $shopBookTime->where('status','in',['undo','doing'])->where('room_id',$val['id'])->where('end_time',">=",time())->select();

            if($val['id'] == 43){

               // error_log("===43==".json_encode($bookList));
    
            }
            $room = $shopRoomModel->where('id',$val['id'])->find();

            if($val['is_clean'] == -1){
                $list[$key]['isClean'] = 1;
            }else{
                $list[$key]['isClean'] = -1;

            }

            foreach ($cleanList as $k2=>$v2){

                if($v2['room_id'] == $val['id']){

                    if($v2['status'] == 'doing'){
                        $list[$key]['isClean'] = 2;
                    }
                }
            }

            if($room['status'] == 'busy'){
                $isFree = false;
            }else{
                $isFree = true;
            }
            $endTime = "";
            $endDate = "";

            foreach ($time as $k=>$v){
                $startDate = $v['time'].":00";
                $startDate2 = $v['time'].":30";

                $startTime = strtotime($startDate);
                $startTime2 = strtotime($startDate2);

                if($val['id'] == 43){
                   // error_log($startDate."====43===".$startDate2);
                }
                $time[$k]['isBook'] = false;



                foreach ($bookList as $k1=>$v1){
                    if($startTime >= $v1['start_time'] && $startTime <= $v1['end_time'] ){
                        $time[$k]['isBook'] = true;
                       //$isFree = false;

                    }
                    if($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']){
                        $time[$k]['isBook'] = true;
                       // $isFree = false;
                    }



                    if($v1['status'] != 'done'){
                        if(time() >= $v1['start_time'] && time()<=$v1['end_time'] ){
                            $list[$key]['useEndTime'] = "使用中".date("H:i",$v1['end_time'])."结束";
                        }
                    }

                    $endTime = date("H:i",strtotime("+20 minute",$v1['end_time']));
                    $endDate = date("Y-m-d",$v1['end_time']);
                }

            }

            $list[$key]['endTime'] =$endTime;
            $list[$key]['endDate'] =$endDate;
            $list[$key]['time'] =$time;
            $list[$key]['isFree'] =$isFree;
            $list[$key]['isCleanBook'] =$isClean;



        }

        $this->success('',$list);
    }


    public function getRoomListV2(){

        $shop_id = $this->request->param('shop_id');
        $spec = $this->request->param('spec');
        $shopRoomModel = new Shoproom();

        if($spec == '') $spec =-1;
//        //根据包厢状态排序，自动将空闲包厢置顶
//        if($spec == -1){
//        }else{
//            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('spec',$spec)->order(['status'=>'asc','weigh'=>'desc'])->select();
//
//        }

        if($spec == -1){
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->order(['weigh'=>'desc'])->select();
        }else{
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('spec',$spec)->order(['weigh'=>'desc'])->select();

        }


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $isClean = $shop['is_clean_book'];
        $shopBookTime = new Shoproombook();
        $roomCleanModel = new Roomclean();

        $cleanList = $roomCleanModel->where('shop_id',$shop_id)->where('start_time',"<",time())->where('end_time',">",time())->where('status','in',['undo','doing'])->select();

        foreach ($list as $key=>$val){


            $setList = $val['set'];

            $setArrayList = array();
            if(count($setList) > 3){
                foreach ($setList as $k=>$v){
                    if($k <2){
                        $setArrayList[] = $v;
                    }
                }
                $list[$key]['set2'] = $setArrayList;
            }else{
                $list[$key]['set2'] = $setList;

            }

            $list[$key]['logo'] = cdnurl($val['logo'],true);

            $covers = explode(",",$val['cover']);
            $cover = array();
            foreach ($covers as $k=>$v){
                if($v != ""){
                    $cover[] =   cdnurl($v,true);
                }
            }
            $list[$key]['cover'] = $cover;
            $tag = explode(",",$val['tag']);
            $tags = array();
            foreach ($tag as $k=>$v){
                if($v != ""){
                    if($k <7){
                        $tags[] = $v;
                    }
                }
            }
            $list[$key]['tag'] = $tags;
            $time = getHourSlot();
            $list[$key]['useEndTime'] = -1;

            $endTime = "";
            $bookList = $shopBookTime->where('status','in',['undo','doing'])->where('room_id',$val['id'])->where('end_time',">=",time())->select();

            if($val['id'] == 43){

                // error_log("===43==".json_encode($bookList));

            }
            $room = $shopRoomModel->where('id',$val['id'])->find();

            if($val['is_clean'] == -1){
                $list[$key]['isClean'] = 1;
            }else{
                $list[$key]['isClean'] = -1;

            }

            foreach ($cleanList as $k2=>$v2){

                if($v2['room_id'] == $val['id']){

                    if($v2['status'] == 'doing'){
                        $list[$key]['isClean'] = 2;
                    }
                }
            }

            if($room['status'] == 'busy'){
                $isFree = false;
            }else{
                $isFree = true;
            }
            $endTime = "";
            $endDate = "";

            foreach ($time as $k=>$v){
                $startDate = $v['time'].":00";
                $startDate2 = $v['time'].":30";

                $startTime = strtotime($startDate);
                $startTime2 = strtotime($startDate2);

                $time[$k]['isBook'] = false;
                $time[$k]['isHalf'] = false;


                $hstart1 = date("H",$startTime2);
                $mstart1 = date("i",$startTime2);
                $mDate1 = date("Y-m-d",$startTime2);

                foreach ($bookList as $k1=>$v1){
                    if($startTime >= $v1['start_time'] && $startTime <= $v1['end_time'] ){
                        $time[$k]['isBook'] = true;
                    }
                    if($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']){
                        $time[$k]['isBook'] = true;
                    }
                   $hstart_1 =  date("H",$v1['start_time']);
                   $mstart_1 =  date("i",$v1['start_time']);
                   $mDate_1 = date("Y-m-d",$v1['start_time']);

                   $hstart_2 =  date("H",$v1['end_time']);
                   $mstart_2 =  date("i",$v1['end_time']);

                   if($hstart_1 == $hstart1 && $mstart_1 >$mstart1 && $mDate_1 == $mDate1){
                       $time[$k]['isBook'] = true;
                   }

                   if($hstart_2 == $hstart1 && $mstart_2 <30 && $mstart_2>0 && $time[$k]['isBook'] ==true){
                       $time[$k]['isHalf'] = true;
                   }

                    if($v1['status'] != 'done'){
                        if(time() >= $v1['start_time'] && time()<=$v1['end_time'] ){
                            $list[$key]['useEndTime'] = "使用中".date("H:i",$v1['end_time'])."结束";
                        }
                    }

                    $endTime = date("H:i",strtotime("+20 minute",$v1['end_time']));
                    $endDate = date("Y-m-d",$v1['end_time']);
                }

            }

            if($endTime == '' && $isFree == false){
                $endTime = date("H:i");
                $endDate = date("Y-m-d");
            }

            $list[$key]['endTime'] =$endTime;
            $list[$key]['endDate'] =$endDate;
            $list[$key]['time'] =$time;
            $list[$key]['isFree'] =$isFree;
            $list[$key]['isCleanBook'] =$isClean;



        }

        $this->success('',$list);
    }


    public function getRoomListV3(){

        $shop_id = $this->request->param('shop_id');
        $spec = $this->request->param('spec');
        $shopRoomModel = new Shoproom();

        if($spec == '') $spec =-1;

        if($spec == -1){
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->order(['weigh'=>'desc'])->select();
        }else{
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('spec',$spec)->order(['weigh'=>'desc'])->select();

        }


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $openStartIndex = -1;
        $openEndIndex = -1;
        $openTime = $shop['open_time'];
        if($openTime != ""){
//            $openStartIndex =  explode("~",$openTime)[0];
//            $openEndIndex =  explode("~",$openTime)[1];
            preg_match('/(\d{2}):\d{2}~(\d{2}):\d{2}/', $openTime, $matches);

            $openStartIndex = $matches[1];  // "08"
            $openEndIndex = $matches[2];    // "02"


        }



        $isClean = $shop['is_clean_book'];
        $shopBookTime = new Shoproombook();
        $roomCleanModel = new Roomclean();

        $cleanList = $roomCleanModel->where('shop_id',$shop_id)->where('start_time',"<",time())->where('end_time',">",time())->where('status','in',['undo','doing'])->select();

        foreach ($list as $key=>$val){


            $setList = $val['set'];

            $setArrayList = array();
            if(count($setList) > 3){
                foreach ($setList as $k=>$v){
                    if($k <2){
                        $setArrayList[] = $v;
                    }
                }
                $list[$key]['set2'] = $setArrayList;
            }else{
                $list[$key]['set2'] = $setList;

            }

            $list[$key]['logo'] = cdnurl($val['logo'],true);

            $covers = explode(",",$val['cover']);
            $cover = array();
            foreach ($covers as $k=>$v){
                if($v != ""){
                    $cover[] =   cdnurl($v,true);
                }
            }
            $list[$key]['cover'] = $cover;
            $tag = explode(",",$val['tag']);
            $tags = array();
            foreach ($tag as $k=>$v){
                if($v != ""){
                    if($k <7){
                        $tags[] = $v;
                    }
                }
            }
            $list[$key]['tag'] = $tags;
            $time = getHourSlot();
            $list[$key]['useEndTime'] = -1;

            $endTime = "";
            $bookList = $shopBookTime->where('status','in',['undo','doing'])->where('room_id',$val['id'])->where('end_time',">=",time())->select();

            $room = $shopRoomModel->where('id',$val['id'])->find();

            if($val['is_clean'] == -1){
                $list[$key]['isClean'] = 1;
            }else{
                $list[$key]['isClean'] = -1;

            }

            foreach ($cleanList as $k2=>$v2){

                if($v2['room_id'] == $val['id']){

                    if($v2['status'] == 'doing'){
                        $list[$key]['isClean'] = 2;
                    }
                }
            }

            if($room['status'] == 'busy'){
                $isFree = false;
            }else{
                $isFree = true;
            }
            $endTime = "";
            $endDate = "";

            foreach ($time as $k=>$v){
                $startDate = $v['time'].":00";
                $startDate2 = $v['time'].":30";

                $startTime = strtotime($startDate);
                $startTime2 = strtotime($startDate2);

                $time[$k]['isBook'] = false;
                $time[$k]['isHalf'] = false;
                $time[$k]['disable'] = false;




                $hstart1 = date("H",$startTime2);
                $mstart1 = date("i",$startTime2);
                $mDate1 = date("Y-m-d",$startTime2);
                if($openStartIndex  != -1){

                    if(intval($hstart1) >=intval($openEndIndex) && intval($hstart1) <= intval($openStartIndex)){
                        $time[$k]['disable'] = true;
                    }
                }

                foreach ($bookList as $k1=>$v1){
                    if($startTime >= $v1['start_time'] && $startTime <= $v1['end_time'] ){
                        $time[$k]['isBook'] = true;
                    }
                    if($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']){
                        $time[$k]['isBook'] = true;
                    }
                    $hstart_1 =  date("H",$v1['start_time']);
                    $mstart_1 =  date("i",$v1['start_time']);
                    $mDate_1 = date("Y-m-d",$v1['start_time']);

                    $hstart_2 =  date("H",$v1['end_time']);
                    $mstart_2 =  date("i",$v1['end_time']);

                    if($hstart_1 == $hstart1 && $mstart_1 >$mstart1 && $mDate_1 == $mDate1){
                        $time[$k]['isBook'] = true;
                    }

                    if($hstart_2 == $hstart1 && $mstart_2 <30 && $mstart_2>0 && $time[$k]['isBook'] ==true){
                        $time[$k]['isHalf'] = true;
                    }

                    if($v1['status'] != 'done'){
                        if(time() >= $v1['start_time'] && time()<=$v1['end_time'] ){
                            $list[$key]['useEndTime'] = "使用中".date("H:i",$v1['end_time'])."结束";
                        }
                    }

                    $endTime = date("H:i",strtotime("+20 minute",$v1['end_time']));
                    $endDate = date("Y-m-d",$v1['end_time']);
                }

            }

            if($endTime == '' && $isFree == false){
                $endTime = date("H:i");
                $endDate = date("Y-m-d");
            }

            $list[$key]['endTime'] =$endTime;
            $list[$key]['endDate'] =$endDate;
            $list[$key]['time'] =$time;
            $list[$key]['isFree'] =$isFree;
            $list[$key]['isCleanBook'] =$isClean;



        }

        $this->success('',$list);
    }



    public function getQpRoomList()
    {
        $shop_id = $this->request->param('shop_id');
        $shopRoomModel = new Shoproom();

        $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('is_ktv',-1)->order(['weigh'=>'desc'])->select();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $openStartIndex = -1;
        $openEndIndex = -1;
        $openTime = $shop['open_time'];
        if($openTime != ""){
//            $openStartIndex =  explode("~",$openTime)[0];
//            $openEndIndex =  explode("~",$openTime)[1];
            preg_match('/(\d{2}):\d{2}~(\d{2}):\d{2}/', $openTime, $matches);

            $openStartIndex = $matches[1];  // "08"
            $openEndIndex = $matches[2];    // "02"



        }



        $isClean = $shop['is_clean_book'];
        $shopBookTime = new Shoproombook();
        $roomCleanModel = new Roomclean();

        $cleanList = $roomCleanModel->where('shop_id',$shop_id)->where('start_time',"<",time())->where('end_time',">",time())->where('status','in',['undo','doing'])->select();

        foreach ($list as $key=>$val){


            $setList = $val['set'];

            $setArrayList = array();
            if(count($setList) > 3){
                foreach ($setList as $k=>$v){
                    if($k <2){
                        $setArrayList[] = $v;
                    }
                }
                $list[$key]['set2'] = $setArrayList;
            }else{
                $list[$key]['set2'] = $setList;

            }

            $list[$key]['logo'] = cdnurl($val['logo'],true);

            $covers = explode(",",$val['cover']);
            $cover = array();
            foreach ($covers as $k=>$v){
                if($v != ""){
                    $cover[] =   cdnurl($v,true);
                }
            }
            $list[$key]['cover'] = $cover;
            $tag = explode(",",$val['tag']);
            $tags = array();
            foreach ($tag as $k=>$v){
                if($v != ""){
                    if($k <7){
                        $tags[] = $v;
                    }
                }
            }
            $list[$key]['tag'] = $tags;
            $time = getHourSlot();
            $list[$key]['useEndTime'] = -1;

            $endTime = "";
            $bookList = $shopBookTime->where('status','in',['undo','doing'])->where('room_id',$val['id'])->where('end_time',">=",time())->select();

            $room = $shopRoomModel->where('id',$val['id'])->find();

            if($val['is_clean'] == -1){
                $list[$key]['isClean'] = 1;
            }else{
                $list[$key]['isClean'] = -1;

            }

            foreach ($cleanList as $k2=>$v2){

                if($v2['room_id'] == $val['id']){

                    if($v2['status'] == 'doing'){
                        $list[$key]['isClean'] = 2;
                    }
                }
            }

            if($room['status'] == 'busy'){
                $isFree = false;
            }else{
                $isFree = true;
            }
            $endTime = "";
            $endDate = "";

            foreach ($time as $k=>$v){
                $startDate = $v['time'].":00";
                $startDate2 = $v['time'].":30";

                $startTime = strtotime($startDate);
                $startTime2 = strtotime($startDate2);

                $time[$k]['isBook'] = false;
                $time[$k]['isHalf'] = false;
                $time[$k]['disable'] = false;




                $hstart1 = date("H",$startTime2);
                $mstart1 = date("i",$startTime2);
                $mDate1 = date("Y-m-d",$startTime2);
                if($openStartIndex  != -1){

                    if(intval($hstart1) >=intval($openEndIndex) && intval($hstart1) <= intval($openStartIndex)){
                        $time[$k]['disable'] = true;
                    }
                }

                foreach ($bookList as $k1=>$v1){
                    if($startTime >= $v1['start_time'] && $startTime <= $v1['end_time'] ){
                        $time[$k]['isBook'] = true;
                    }
                    if($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']){
                        $time[$k]['isBook'] = true;
                    }
                    $hstart_1 =  date("H",$v1['start_time']);
                    $mstart_1 =  date("i",$v1['start_time']);
                    $mDate_1 = date("Y-m-d",$v1['start_time']);

                    $hstart_2 =  date("H",$v1['end_time']);
                    $mstart_2 =  date("i",$v1['end_time']);

                    if($hstart_1 == $hstart1 && $mstart_1 >$mstart1 && $mDate_1 == $mDate1){
                        $time[$k]['isBook'] = true;
                    }

                    if($hstart_2 == $hstart1 && $mstart_2 <30 && $mstart_2>0 && $time[$k]['isBook'] ==true){
                        $time[$k]['isHalf'] = true;
                    }

                    if($v1['status'] != 'done'){
                        if(time() >= $v1['start_time'] && time()<=$v1['end_time'] ){
                            $list[$key]['useEndTime'] = "使用中".date("H:i",$v1['end_time'])."结束";
                        }
                    }

                    $endTime = date("H:i",strtotime("+20 minute",$v1['end_time']));
                    $endDate = date("Y-m-d",$v1['end_time']);
                }

            }

            if($endTime == '' && $isFree == false){
                $endTime = date("H:i");
                $endDate = date("Y-m-d");
            }

            $list[$key]['endTime'] =$endTime;
            $list[$key]['endDate'] =$endDate;
            $list[$key]['time'] =$time;
            $list[$key]['isFree'] =$isFree;
            $list[$key]['isCleanBook'] =$isClean;



        }

        $this->success('',$list);
    }
    public function getRoomListV4(){

        $shop_id = $this->request->param('shop_id');
        $spec = $this->request->param('spec');
        $shopRoomModel = new Shoproom();

        if($spec == '') $spec =-1;

        if($spec == -1){
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('is_ktv',1)->order(['weigh'=>'desc'])->select();
        }else{
            $list = $shopRoomModel->with(['set'])->where('shop_id',$shop_id)->where('is_ktv',1)->where('spec',$spec)->order(['weigh'=>'desc'])->select();

        }


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->find();
        $openStartIndex = -1;
        $openEndIndex = -1;
        $openTime = $shop['open_time'];
        if($openTime != ""){
//            $openStartIndex =  explode("~",$openTime)[0];
//            $openEndIndex =  explode("~",$openTime)[1];
            preg_match('/(\d{2}):\d{2}~(\d{2}):\d{2}/', $openTime, $matches);

            $openStartIndex = $matches[1];  // "08"
            $openEndIndex = $matches[2];    // "02"


            error_log($openStartIndex."===dd====".$openEndIndex);

        }



        $isClean = $shop['is_clean_book'];
        $shopBookTime = new Shoproombook();
        $roomCleanModel = new Roomclean();

        $cleanList = $roomCleanModel->where('shop_id',$shop_id)->where('start_time',"<",time())->where('end_time',">",time())->where('status','in',['undo','doing'])->select();

        foreach ($list as $key=>$val){


            $setList = $val['set'];

            $setArrayList = array();
            if(count($setList) > 3){
                foreach ($setList as $k=>$v){
                    if($k <2){
                        $setArrayList[] = $v;
                    }
                }
                $list[$key]['set2'] = $setArrayList;
            }else{
                $list[$key]['set2'] = $setList;

            }

            $list[$key]['logo'] = cdnurl($val['logo'],true);

            $covers = explode(",",$val['cover']);
            $cover = array();
            foreach ($covers as $k=>$v){
                if($v != ""){
                    $cover[] =   cdnurl($v,true);
                }
            }
            $list[$key]['cover'] = $cover;
            $tag = explode(",",$val['tag']);
            $tags = array();
            foreach ($tag as $k=>$v){
                if($v != ""){
                    if($k <7){
                        $tags[] = $v;
                    }
                }
            }
            $list[$key]['tag'] = $tags;
            $time = getHourSlot();
            $list[$key]['useEndTime'] = -1;

            $endTime = "";
            $bookList = $shopBookTime->where('status','in',['undo','doing'])->where('room_id',$val['id'])->where('end_time',">=",time())->select();

            $room = $shopRoomModel->where('id',$val['id'])->find();

            if($val['is_clean'] == -1){
                $list[$key]['isClean'] = 1;
            }else{
                $list[$key]['isClean'] = -1;

            }

            foreach ($cleanList as $k2=>$v2){

                if($v2['room_id'] == $val['id']){

                    if($v2['status'] == 'doing'){
                        $list[$key]['isClean'] = 2;
                    }
                }
            }

            if($room['status'] == 'busy'){
                $isFree = false;
            }else{
                $isFree = true;
            }
            $endTime = "";
            $endDate = "";

            foreach ($time as $k=>$v){
                $startDate = $v['time'].":00";
                $startDate2 = $v['time'].":30";

                $startTime = strtotime($startDate);
                $startTime2 = strtotime($startDate2);

                $time[$k]['isBook'] = false;
                $time[$k]['isHalf'] = false;
                $time[$k]['disable'] = false;




                $hstart1 = date("H",$startTime2);
                $mstart1 = date("i",$startTime2);
                $mDate1 = date("Y-m-d",$startTime2);
                if($openStartIndex  != -1){

                    if(intval($hstart1) >=intval($openEndIndex) && intval($hstart1) <= intval($openStartIndex)){
                        $time[$k]['disable'] = true;
                    }
                }

                foreach ($bookList as $k1=>$v1){
                    if($startTime >= $v1['start_time'] && $startTime <= $v1['end_time'] ){
                        $time[$k]['isBook'] = true;
                    }
                    if($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']){
                        $time[$k]['isBook'] = true;
                    }
                    $hstart_1 =  date("H",$v1['start_time']);
                    $mstart_1 =  date("i",$v1['start_time']);
                    $mDate_1 = date("Y-m-d",$v1['start_time']);

                    $hstart_2 =  date("H",$v1['end_time']);
                    $mstart_2 =  date("i",$v1['end_time']);

                    if($hstart_1 == $hstart1 && $mstart_1 >$mstart1 && $mDate_1 == $mDate1){
                        $time[$k]['isBook'] = true;
                    }

                    if($hstart_2 == $hstart1 && $mstart_2 <30 && $mstart_2>0 && $time[$k]['isBook'] ==true){
                        $time[$k]['isHalf'] = true;
                    }

                    if($v1['status'] != 'done'){
                        if(time() >= $v1['start_time'] && time()<=$v1['end_time'] ){
                            $list[$key]['useEndTime'] = "使用中".date("H:i",$v1['end_time'])."结束";
                        }
                    }

                    $endTime = date("H:i",strtotime("+20 minute",$v1['end_time']));
                    $endDate = date("Y-m-d",$v1['end_time']);
                }

            }

            if($endTime == '' && $isFree == false){
                $endTime = date("H:i");
                $endDate = date("Y-m-d");
            }

            $list[$key]['endTime'] =$endTime;
            $list[$key]['endDate'] =$endDate;
            $list[$key]['time'] =$time;
            $list[$key]['isFree'] =$isFree;
            $list[$key]['isCleanBook'] =$isClean;



        }

        $this->success('',$list);
    }


    //最近5天的时间
    public function roomTime(){

        $time = getFiveDate();
        $this->success('',$time);
    }


    /**
     * 时间区间获取
     */
    public function roomTimeOne(){

        $room_id = $this->request->param('id');
        $date = $this->request->param('date');

        $next = getNextTime();
        if($date == date("Y-m-d")){
            $timeList = getTimeList();

        }else{
            $timeList = getTimeList2();
        }


        foreach ($next as $key=>$val){
            $timeList[] = $val;
        }



        $startTime = strtotime($date." 00:00:00");
        $endTime = strtotime($date." 23:59:59");

        $shopBookTime = new Shoproombook();
        $bookList = $shopBookTime->where('room_id',$room_id)->where('status',"<>",'done')->select();


        $cleanRoomModel = new Roomclean();
        $cleanList = $cleanRoomModel->where('room_id',$room_id)->where('status',"<>",'done')->select();
        $nextDate = strtotime("+1 day",strtotime($date));
        $nextDate = date("Y-m-d",$nextDate);

        foreach ($timeList as $key=>$val){

            $start = explode("-",$val['time'])[0];
            $end = explode("-",$val['time'])[1];


            if($val['prefx'] ==''){
                $startTime = strtotime($date." ".$start);
                $endTime = strtotime($date." ".$end);
            }else{
                $startTime = strtotime($nextDate." ".$start);
                $endTime = strtotime($nextDate." ".$end);
            }



            $timeList[$key]['selected'] = false;
            $timeList[$key]['isFree'] = true;
            $timeList[$key]['isUseing'] = false;


            foreach ($bookList as $k =>$v){
                if(($startTime >= $v['start_time'] && $endTime< $v['end_time']) || ($v['end_time'] > $startTime && $v['end_time']  <= $endTime) || ($v['start_time'] > $startTime && $v['start_time']  < $endTime)){
                    $timeList[$key]['isFree'] = false;
                    if(time() >= $startTime && time()<=$endTime){
                        $timeList[$key]['isUseing'] = true;
                    }
                }

            }
            $timeList[$key]['isClean'] = false;

            foreach ($cleanList as $k =>$v){
                if(($startTime >= $v['start_time'] && $endTime<= $v['end_time']) || ($v['end_time'] > $startTime && $v['end_time']  < $endTime)){
                    if($v['status'] != 'done'){
                        $timeList[$key]['isClean'] = true;
                    }
                }

            }




        }

        $this->success('',$timeList);
    }

    /**
     * 按小时获取
     */
    public function roomTimeTwo(){

        $ret = array();
        $room_id = $this->request->param('id');
        $date = $this->request->param('date');
        $hour = $this->request->param('hour');

        $today = date("Y-m-d");
        if($today == $date){
            //今天 ，从当前时间来计算
        }else{

        }


        $this->success('',$ret);
    }


    /**
     * 按套餐获取
     */
    public function roomTimeThree(){

        $ret = array();
        $room_id = $this->request->param('id');
        $date = $this->request->param('date');

        $roomSetModel = new Shoproomset();
        $list = $roomSetModel->where('room_id',$room_id)->select();
        $ret['list'] = $list;
        $this->success('',$ret);
    }

    /**
     * 余额可用门店
     */
    public function balanceShopList(){
        $id = $this->request->param('id');
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$id)->find();
        $shop['logo'] = cdnurl($shop['logo'],true);

        $covers = explode(",",$shop['cover']);
        $tag = explode(",",$shop['tag']);
        $cover = array();
        foreach ($covers as $key=>$val){
            $cover[] = cdnurl($val,true);
        }
        $shop['cover']= $cover;
        $shop['tag']= $tag;
        $list = array();
        $list[] = $shop;
        $this->success('',$list);
    }


    /**
     * 店铺wifi信息
     */
    public function getWifiInfo(){

       $shop_id =  $this->request->param('shop_id');
       $shopWifiModel = new Shopwifi();
       $wifi = $shopWifiModel->where('shop_id',$shop_id)->find();
       if(!$wifi){
           $this->error("店铺暂未设置wifi信息");
       }else{
           $this->success('',$wifi);
       }
    }


    public function getNotice(){

        $shop_id =  $this->request->param('shop_id');
        $noticeModel = new Notice();
        $notice = $noticeModel->where('shop_id',$shop_id)->order('create_time','desc')->find();

        if($notice){
            $contents = explode(",",$notice['content']);
            $newList = array();

            if(count($contents) >0){
                foreach ($contents as $key=>$val){
                    $obj = array();
                    $obj['content'] = $val;
                    $newList[] = $obj;

                }
            }
            $notice['content'] = $newList;
        }

        $this->success('',$notice);
    }

    //门店约满提示
    public function getNotice1()
    {

        $shop_id = $this->request->param('shop_id');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        if (empty($lat)) {
            $lat = '28.1475470';
            $lng = '113.0265810';
        }
        $page = 1;
        $limit = 3;
        $offset = ($page - 1) * $limit;

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $shop_id)->find();

        $noticeModel = new Notice();
        $notice = $noticeModel->where('shop_id', $shop_id)->order('create_time', 'desc')->find();
        $is_notice = false;
        if ($notice) {
            $contents = explode(",", $notice['content']);
            $newList = array();

            if (count($contents) > 0) {
                $is_notice = true;
                foreach ($contents as $key => $val) {
                    $obj = array();
                    $obj['content'] = $val;
                    $newList[] = $obj;
                }
            }
            $notice['content'] = $newList;
        }
        $notice['is_notice'] = $is_notice;

        //检测店铺包厢使用情况（综合门店除外）
        $roomModel = new Shoproom();
        $roomNum = $roomModel->where('shop_id', $shop_id)->count('id');
        $useRoomNum = $roomModel->where('shop_id', $shop_id)->where('status','in',['stop','busy'])->count('id');
        $notice['is_room_full'] = false;
        $notice['nearby_shop'] = array();
        if ($roomNum == $useRoomNum && $roomNum > 0 && $shop['is_table'] == -1) {
            $notice['is_room_full'] = true;

            $where = "and is_fake = -1 and id !=" . $shop_id;

            $sql = "select * from(
SELECT id,name,city,address,logo,lng,is_ktv,lat,tel,is_table,status,temp_shop_id,shop_type,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop where `status` in(1,2) $where) as tmp_table_name
order by distance LIMIT $offset ,$limit";
            $shopModel = new \app\admin\model\Shop();
            $list = $shopModel->query($sql);
            $newList = array();
            foreach ($list as $v) {
                $newArr = array();
                $newArr['id'] = $v['id'];
                $newArr['name'] = $v['name'];
                $newArr['address'] = $this->splitIfContains($v['address'], $v['city']);
                if ($v['distance'] < 5000) {//限制5公里内展示附近门店
                    $newArr['distance'] = formatMoney($v['distance'] / 1000) . 'km';
                    $newList[] = $newArr;
                }

            }

            $notice['nearby_shop'] = $newList;
        }

        if (empty($notice['nearby_shop'])) {
            $notice['is_room_full'] = false;
        }

        $this->success('', $notice);
    }

    protected function splitIfContains($haystack, $needle)
    {
        // 检查 $haystack 是否包含 $needle
        if (str_contains($haystack, $needle)) {
            $position = strpos($haystack, $needle);
            $partBeforeNeedle = substr($haystack, 0, $position);
            if ($partBeforeNeedle === '') {
                return $haystack;
            }

            $haystackWithoutNeedle = str_replace($needle, '', $haystack);

            $result = explode($partBeforeNeedle, $haystackWithoutNeedle);
            return $result[1];
        } else {
            // 如果不包含，返回原字符串
            return $haystack;
        }
    }

    public function doShopFav(){

        $user = $this->auth->getUser();
        $shop_id = $this->request->param('shop_id');

        $shopFavModel = new Shopfav();
        $fav = $shopFavModel->where('shop_id',$shop_id)->where('user_id',$user['id'])->find();
        if($fav){
            $shopFavModel->where('id',$fav['id'])->delete();
            $isFav = -1;
        }else{
            $shopFavModel->insert(['user_id'=>$user['id'],'shop_id'=>$shop_id]);
            $isFav = 1;
        }
        $this->success("",$isFav);
    }

    public function favShopList(){

        $user = $this->auth->getUser();
        $shopFavModel = new Shopfav();
        $list = $shopFavModel->with(['shop'])->where('Shopfav.user_id',$user['id'])->select();
        foreach ($list as $key=>$val){
            $list[$key]['shop']['logo'] = cdnurl($val['shop']['logo'],true);
        }
        $this->success('',$list);
    }

    public function roomInfo(){

        $id = $this->request->param('id');
        $shopRoomModel = new Shoproom();
        $shopModel = new \app\admin\model\Shop();
        $room = $shopRoomModel->where('id',$id)->find();
        $shop = $shopModel->where('id',$room['shop_id'])->find();
        $ret = array();
        $ret['room_name'] = $room['name'];
        $ret['shop_name'] = $shop['name'];
        $this->success('',$ret);
    }


    public function codeChargeInfo()
    {

        $code = $this->request->param('code');
        $chargeCodeModel = new Chargecode();
        $chargeCode = $chargeCodeModel->where('code',$code)->find();
        if(!$chargeCode) $this->error("兑换码不存在");
        if($chargeCode['status'] == 'used') $this->error("兑换码已兑换");


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$chargeCode['shop_id'])->find();

        $ret = array();
        $ret['shop_name'] = $shop['name'];
        $ret['amount'] = $chargeCode['price'];
        $this->success('',$ret);
    }

    public function doCodeCharge()
    {

        $code = $this->request->param('code');
        $chargeCodeModel = new Chargecode();
        $chargeCode = $chargeCodeModel->where('code',$code)->find();
        if(!$chargeCode) $this->error("兑换码不存在");
        if($chargeCode['status'] == 'used') $this->error("兑换码已兑换");


        $balanceModel = new Userbalance();
        $balance = $balanceModel->where('charge_code',$code)->find();
        if($balance) $this->error("此券不能兑换");
        $chargeCodeModel->where('id',$chargeCode['id'])->update(['status'=>'used']);

        $user = $this->auth->getUser();
        $balanceModel->insert(['user_id'=>$user['id'],'type'=>'in','amount'=>$chargeCode['price'],
            'mark'=>'充值卡兑换','create_time'=>time(),'shop_id'=>$chargeCode['shop_id'],'order_id'=>-1,'charge_code'=>$code]);
        $this->success('兑换成功');
    }



    public function getMallShopList()
    {

        $keyword = $this->request->param('keyword');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');

        if(!$lat){
            $lat =28.2068360;
            $lng =112.8823270;
        }

        $orgId = $this->request->param('orgId');

        $where = "where mall_id != -1";
        if ($keyword != '') {
            $where =" and name like '%".$keyword."%'";
        }

        $sql = "select * from(
SELECT id,name,address,logo,lng,lat,is_join_balance,qun_url,org_id,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop  $where )  as tmp_table_name
order by distance";

        // error_log("==sql==".$sql);
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->query($sql);
        foreach ($list as $key=>$val){
            $list[$key]['qun_url'] = cdnurl($val['qun_url'],true);
            $list[$key]['distance'] = formatMoney($val['distance'] / 1000) . 'km';
            $list[$key]['distance2'] = $val['distance'];


        }
        $this->success('', $list);
    }


}
